
const express = require('express');
const axios = require('axios');
const router = express.Router();

// Middleware to check authentication
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: 'Access token required' });
  }

  const jwt = require('jsonwebtoken');
  jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key', (err, user) => {
    if (err) return res.status(403).json({ error: 'Invalid token' });
    req.user = user;
    next();
  });
};

// Create annual plan
router.post('/annual', authenticateToken, (req, res) => {
  const { title, description, objectives, year } = req.body;
  const db = req.db;

  db.run(
    'INSERT INTO annual_plans (user_id, year, title, description, objectives) VALUES (?, ?, ?, ?, ?)',
    [req.user.userId, year, title, description, objectives],
    function (err) {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      res.status(201).json({ id: this.lastID, message: 'Annual plan created successfully' });
    }
  );
});

// Get annual plans
router.get('/annual', authenticateToken, (req, res) => {
  const db = req.db;
  const userId = req.user.role === 'manager' ? req.query.userId : req.user.userId;

  db.all(
    'SELECT * FROM annual_plans WHERE user_id = ? ORDER BY year DESC',
    [userId || req.user.userId],
    (err, plans) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      res.json(plans);
    }
  );
});

// Create monthly plan
router.post('/monthly', authenticateToken, (req, res) => {
  const { month, year, title, description, objectives, tasks } = req.body;
  const db = req.db;

  // 暂时不插入tasks字段，先让月度计划创建成功
  // const tasksJson = tasks ? JSON.stringify(tasks) : null;

  db.run(
    'INSERT INTO monthly_plans (user_id, month, year, title, description, objectives, annual_plan_id) VALUES (?, ?, ?, ?, ?, ?, ?)',
    [req.user.userId, month, year, title, description, objectives, req.body.annual_plan_id || null],
    function (err) {
      if (err) {
        console.error('月度计划插入数据库错误:', err)
        console.error('SQL错误详情:', err.message)
        return res.status(500).json({ error: 'Database error' });
      }
      console.log('月度计划创建成功，ID:', this.lastID)
      res.status(201).json({ id: this.lastID, message: 'Monthly plan created successfully' });
    }
  );
});

// Get monthly plans
router.get('/monthly', authenticateToken, (req, res) => {
  const db = req.db;
  const userId = req.user.role === 'manager' ? req.query.userId : req.user.userId;

  db.all(
    'SELECT * FROM monthly_plans WHERE user_id = ? ORDER BY year DESC, month DESC',
    [userId || req.user.userId],
    (err, plans) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }

      // 解析tasks JSON字符串
      const plansWithTasks = plans.map(plan => {
        if (plan.tasks) {
          try {
            plan.tasks = JSON.parse(plan.tasks);
          } catch (error) {
            console.error('解析tasks JSON失败:', error);
            plan.tasks = [];
          }
        } else {
          plan.tasks = [];
        }
        return plan;
      });

      res.json(plansWithTasks);
    }
  );
});

// Create weekly plan
router.post('/weekly', authenticateToken, (req, res) => {
  const { week, month, year, title, description, objectives } = req.body;
  const db = req.db;

  db.run(
    'INSERT INTO weekly_plans (user_id, week, month, year, title, description, objectives) VALUES (?, ?, ?, ?, ?, ?, ?)',
    [req.user.userId, week, month, year, title, description, objectives],
    function (err) {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      res.status(201).json({ id: this.lastID, message: 'Weekly plan created successfully' });
    }
  );
});

// Get weekly plans
router.get('/weekly', authenticateToken, (req, res) => {
  const db = req.db;
  const userId = req.user.role === 'manager' ? req.query.userId : req.user.userId;

  db.all(
    'SELECT * FROM weekly_plans WHERE user_id = ? ORDER BY year DESC, month DESC, week DESC',
    [userId || req.user.userId],
    (err, plans) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      res.json(plans);
    }
  );
});

// Update plan
router.put('/:type/:id', authenticateToken, (req, res) => {
  const { type, id } = req.params;
  const { title, description, objectives, year, month, week, tasks } = req.body;
  const db = req.db;

  const tableMap = {
    'annual': 'annual_plans',
    'monthly': 'monthly_plans',
    'weekly': 'weekly_plans'
  };

  const table = tableMap[type];
  if (!table) {
    return res.status(400).json({ error: 'Invalid plan type' });
  }

  let updateFields = [];
  let values = [];

  if (title) {
    updateFields.push('title = ?');
    values.push(title);
  }
  if (description) {
    updateFields.push('description = ?');
    values.push(description);
  }
  if (objectives) {
    updateFields.push('objectives = ?');
    values.push(objectives);
  }
  if (year) {
    updateFields.push('year = ?');
    values.push(year);
  }
  if (month) {
    updateFields.push('month = ?');
    values.push(month);
  }
  if (week) {
    updateFields.push('week = ?');
    values.push(week);
  }
  if (tasks !== undefined) {
    // 将tasks数组转换为JSON字符串存储
    const tasksJson = tasks ? JSON.stringify(tasks) : null;
    updateFields.push('tasks = ?');
    values.push(tasksJson);
  }

  updateFields.push('updated_at = CURRENT_TIMESTAMP');

  if (updateFields.length === 0) {
    return res.status(400).json({ error: 'No fields to update' });
  }

  values.push(id, req.user.userId);

  db.run(
    `UPDATE ${table} SET ${updateFields.join(', ')} WHERE id = ? AND user_id = ?`,
    values,
    function (err) {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      if (this.changes === 0) {
        return res.status(404).json({ error: 'Plan not found' });
      }
      res.json({ message: 'Plan updated successfully' });
    }
  );
});

// Delete plan
router.delete('/:type/:id', authenticateToken, (req, res) => {
  const { type, id } = req.params;
  const db = req.db;

  const tableMap = {
    'annual': 'annual_plans',
    'monthly': 'monthly_plans',
    'weekly': 'weekly_plans'
  };

  const table = tableMap[type];
  if (!table) {
    return res.status(400).json({ error: 'Invalid plan type' });
  }

  db.run(
    `DELETE FROM ${table} WHERE id = ? AND user_id = ?`,
    [id, req.user.userId],
    function (err) {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      if (this.changes === 0) {
        return res.status(404).json({ error: 'Plan not found' });
      }
      res.json({ message: 'Plan deleted successfully' });
    }
  );
});

// Update plan status
router.put('/:type/:id/status', authenticateToken, (req, res) => {
  const { type, id } = req.params;
  const { status } = req.body;
  const db = req.db;

  const tableMap = {
    'annual': 'annual_plans',
    'monthly': 'monthly_plans',
    'weekly': 'weekly_plans'
  };

  const table = tableMap[type];
  if (!table) {
    return res.status(400).json({ error: 'Invalid plan type' });
  }

  db.run(
    `UPDATE ${table} SET status = ? WHERE id = ? AND user_id = ?`,
    [status, id, req.user.userId],
    function (err) {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      if (this.changes === 0) {
        return res.status(404).json({ error: 'Plan not found' });
      }
      res.json({ message: 'Plan status updated successfully' });
    }
  );
});

// Helper function to call DeepSeek API (Copied from reports.js/ai-suggestions.js to avoid circular deps for now)
async function generateAIContent(prompt, maxRetries = 3, maxTokens = 2000) {
  let lastError;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      console.log(`AI API Call Attempt ${attempt}/${maxRetries}`);

      const response = await axios.post('https://api.deepseek.com/v1/chat/completions', {
        model: 'deepseek-chat',
        messages: [
          {
            role: 'system',
            content: 'You are a professional AI assistant specializing in project management and work reporting. Your output should be professional, concise, and action-oriented.'
          },
          { role: 'user', content: prompt }
        ],
        max_tokens: maxTokens,
        temperature: 0.5
      }, {
        headers: {
          'Authorization': `Bearer ${process.env.DEEPSEEK_API_KEY}`,
          'Content-Type': 'application/json'
        },
        timeout: 30000
      });

      return response.data.choices[0].message.content;

    } catch (error) {
      lastError = error;
      console.error(`AI API Call Failed (${attempt}/${maxRetries}):`, error.message);

      if (error.response?.status === 429) {
        const waitTime = 2000 * attempt;
        await new Promise(resolve => setTimeout(resolve, waitTime));
        continue;
      }

      if (error.response?.status === 401) {
        throw new Error('Invalid API Key');
      }
    }
  }

  throw lastError || new Error('AI Service Unavailable');
}

// Generate weekly plans from monthly plan
router.post('/weekly/generate-from-monthly', authenticateToken, async (req, res) => {
  const { monthlyPlanId } = req.body;
  const db = req.db;

  try {
    // 1. Get Monthly Plan
    const monthlyPlan = await new Promise((resolve, reject) => {
      db.get('SELECT * FROM monthly_plans WHERE id = ? AND user_id = ?', [monthlyPlanId, req.user.userId], (err, row) => {
        if (err) reject(err);
        else resolve(row);
      });
    });

    if (!monthlyPlan) {
      return res.status(404).json({ error: 'Monthly plan not found' });
    }

    // 2. Generate Weekly Breakdown using AI
    const prompt = `
    Task: Break down the following Monthly Plan into 4 Weekly Plans.
    
    Monthly Plan:
    Title: ${monthlyPlan.title}
    Description: ${monthlyPlan.description}
    Objectives: ${monthlyPlan.objectives}
    Tasks: ${monthlyPlan.tasks || 'Not specified'}
    
    Requirements:
    1. Create exactly 4 weekly plans (Week 1 to Week 4).
    2. Distribute the monthly tasks logically across the weeks.
    3. **IMPORTANT**: The output MUST be in **Simplified Chinese**.
    4. **IMPORTANT**: The output MUST be a valid JSON array of objects.
    
    Return Format (JSON Array):
    [
      {
        "week": 1,
        "title": "Week 1 Title",
        "description": "...",
        "objectives": "..."
      },
      ...
    ]
    `;

    const aiResponse = await generateAIContent(prompt);
    let weeklyPlansData = [];

    try {
      const jsonMatch = aiResponse.match(/\[[\s\S]*\]/);
      const jsonString = jsonMatch ? jsonMatch[0] : aiResponse;
      weeklyPlansData = JSON.parse(jsonString);
    } catch (e) {
      console.error('AI JSON Parse Failed:', e);
      return res.status(500).json({ error: 'Failed to parse AI response' });
    }

    // 3. Insert Weekly Plans
    let generatedCount = 0;
    const insertPromises = weeklyPlansData.map(plan => {
      return new Promise((resolve, reject) => {
        db.run(
          'INSERT INTO weekly_plans (user_id, week, month, year, title, description, objectives) VALUES (?, ?, ?, ?, ?, ?, ?)',
          [req.user.userId, plan.week, monthlyPlan.month, monthlyPlan.year, plan.title, plan.description, plan.objectives],
          function (err) {
            if (err) reject(err);
            else {
              generatedCount++;
              resolve(this.lastID);
            }
          }
        );
      });
    });

    await Promise.all(insertPromises);

    res.json({ message: 'Weekly plans generated successfully', generated: generatedCount });

  } catch (error) {
    console.error('Generate weekly plans error:', error);
    res.status(500).json({ error: 'Failed to generate weekly plans' });
  }
});

module.exports = router;
